﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Services.Client;
using System.Xml.Linq;
using System.Reflection;

namespace GiveAQuiz.Client.Data.DataServices
{
  public partial class GiveAQuizEntities : global::System.Data.Services.Client.DataServiceContext
  {
    // Using technique to ignore certain properties from
    // http://blogs.msdn.com/phaniraj/archive/2008/12/11/customizing-serialization-of-entities-in-the-ado-net-data-services-client-library.aspx
    public GiveAQuizEntities(Uri dataServiceUri, bool enableIgnoreProperties)
      : this(dataServiceUri)
    {
      if (enableIgnoreProperties)
      {
        // This allows us to control the serialization of the entities
        // to allow us to ignore certain properties 
        this.WritingEntity += GiveAQuizEntities_WritingEntity;
      }

      // Add the security header
      this.SendingRequest += (s, e) =>
        {
          //string key = SecurityKeyGenerator.GenerateKey(this.BaseUri.ToString());
          //e.RequestHeaders[SecurityParameters.HEADERNAME] = key;
        };
    }

    void GiveAQuizEntities_WritingEntity(object sender, ReadingWritingEntityEventArgs e)
    {
      // e.Data gives you the XElement for the Serialization of the Entity 
      // Using XLinq  , you can  add/Remove properties to the element Payload  
      XName xnEntityProperties = XName.Get("properties", e.Data.GetNamespaceOfPrefix("m").NamespaceName);
      XElement xePayload = null;
      foreach (PropertyInfo property in e.Entity.GetType().GetProperties())
      {
        object[] doNotSerializeAttributes = property.GetCustomAttributes(typeof(DoNotSerializeAttribute), false);
        if (doNotSerializeAttributes.Length > 0)
        {
          if (xePayload == null)
          {
            xePayload = e.Data.Descendants().Where<XElement>(xe => xe.Name == xnEntityProperties).First<XElement>();
          }
          // The XName of the property we are going to remove from the payload
          XName xnProperty = XName.Get(property.Name, e.Data.GetNamespaceOfPrefix("d").NamespaceName);
          // Get the Property of the entity  you don't want sent to the server
          XElement xeRemoveThisProperty = xePayload
               .Descendants()
               .Where<XElement>(xe => xe.Name == xnProperty)
               .First<XElement>();
          // Remove this property from the Payload sent to the server 
          xeRemoveThisProperty.Remove();

        }
      }
    }

  }
}
